

#include <stdio.h>
#include "cmsis_os2.h"
#include "ohos_run.h"
#include <stdio.h>
#include "driver/uart.h"
#include "driver/gpio.h"
#include "sdkconfig.h"
#include "esp_log.h"

#define SYS_DELAY_TICKS 200
#define TASK_STACK_SIZE 4096
#define TASK_PRIO 25 

osThreadId_t g_taskID = NULL;

//定义串口的引脚
#define ECHO_TEST_TXD (GPIO_NUM_19)
#define ECHO_TEST_RXD (GPIO_NUM_21)
#define ECHO_TEST_RTS (UART_PIN_NO_CHANGE)
#define ECHO_TEST_CTS (UART_PIN_NO_CHANGE)

#define ECHO_UART_PORT_NUM      (UART_NUM_2)
#define ECHO_UART_BAUD_RATE     (115200)


#define BUF_SIZE (1024)




static void uart_test(void)
{
    /* Configure parameters of an UART driver,
     * communication pins and install the driver */
    uart_config_t uart_config = {
        .baud_rate = ECHO_UART_BAUD_RATE,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
    };
    int intr_alloc_flags = 0;

#if CONFIG_UART_ISR_IN_IRAM
    intr_alloc_flags = ESP_INTR_FLAG_IRAM;
#endif
    if(uart_param_config(ECHO_UART_PORT_NUM, &uart_config) == ESP_OK)
    {
        printf("uart config ok\r\n");
    }
    else
    {
        printf("uart config failed\r\n");
    }
    
    if( uart_set_pin(ECHO_UART_PORT_NUM, ECHO_TEST_TXD, ECHO_TEST_RXD, -1, -1) == ESP_OK)
    {
        printf("uart set pin ok\r\n");
    }
    else
    {
        printf("uart set pin failed\r\n");
    }

    if(uart_driver_install(ECHO_UART_PORT_NUM, BUF_SIZE, BUF_SIZE, 0, NULL, 0) == ESP_OK)
    {
        printf("uart driver install ok\r\n");
    }
    else
    {
        printf("driver install failed\r\n");
    }


    // Configure a temporary buffer for the incoming data
    uint8_t *data = (uint8_t *) malloc(BUF_SIZE);

    // Write data back to the UART
    uart_write_bytes(ECHO_UART_PORT_NUM, "AT\r\n", strlen("AT\r\n"));

    printf("start recv uart!\n");
    while (1) {
        // Read data from the UART
        int len = uart_read_bytes(ECHO_UART_PORT_NUM, data, (BUF_SIZE - 1), pdMS_TO_TICKS(50));//接受BUF_SIZE-1个数据，若50ms后还没接受满也立即返回，返回值为实际接受的字符数
        
        if (len > 0) {
            data[len] = '\0';
            printf("recv %s", (char *) data);
            //uart_flush(ECHO_UART_PORT_NUM);                   //清空缓冲区
        }
    }
    printf("---> Exit uart_test task!\r\n");
    return;
}

static void uart_example_task(void)
{
    osThreadAttr_t attr;
    attr.name = "uart_test";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = TASK_PRIO;
    g_taskID = osThreadNew((osThreadFunc_t)uart_test, NULL, &attr);
    if (g_taskID == NULL) {
        printf("Failed to create Test Uart thread!\n");
    }
}

OHOS_APP_RUN(uart_example_task);
